package DAO.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Query;

import DAO.HibernateUtil;
import DAO.TicketDAO;
import DAO.TrainDAO;

import model.impl.Passenger;
import model.impl.Ticket;
import model.impl.Train;

public class TrainDAOImpl extends GenericDAOImpl<Train, Integer> implements
	TrainDAO {

	public List<Passenger> getAllPassangersOnTheTrain(Train train) {
		TicketDAO ticketDAO = new TicketDAOImpl();
		List<Passenger> passengers = null;
		try {
			HibernateUtil.beginTransaction();
			passengers = new ArrayList<Passenger>(); 
			List<Ticket> passengersTicket = null;
			String sqlRequest = "SELECT t FROM Ticket t WHERE t.train = :givenTrain";
			Query query = HibernateUtil.getSession().createQuery(sqlRequest).setParameter("givenTrain", train);
			passengersTicket = ticketDAO.findMany(query);
			for(int i = 0; i < passengersTicket.size(); i++) {
				passengers.add(passengersTicket.get(i).getPassenger());
			}
			HibernateUtil.commitTransaction();
		} catch (Exception e) {
			HibernateUtil.rollbackTransaction();
            System.out.println("Error in getAllPassengers");
            e.printStackTrace();
        }
		return passengers;
	}
	
	
	public Train findTrainByTrainNumber(Integer trainNum) {
		Train train = null;
		try {
			HibernateUtil.beginTransaction();
			String sqlRequest = "SELECT t FROM Train t WHERE t.trainNumber = :trainNum";
			Query query = HibernateUtil.getSession().createQuery(sqlRequest).setParameter("trainNum", trainNum);
			train = findOne(query);
			HibernateUtil.commitTransaction();
		} catch (Exception e) {
			HibernateUtil.rollbackTransaction();
            System.out.println("Error in findTrainByTrainNumber");
            e.printStackTrace();
        }
		return train;
	}
}
